package exam;

import java.io.PrintWriter;
import java.io.Serial;
import java.io.Serializable;
import java.util.*;

public class Test02 {
    // 要求：控制台按照学生属性要求输入学生信息，当输入的内容为exit退出；
    // 将输入的学生信息分别封装进一个Student对象，并将Student对象加入到一个集合中，要求集合中的元素按照年龄的大小正序排列，最后遍历将集合中的学生信息写入一个记事本中
    // 每个学生独占一行；

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //1.创建集合
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge();//年龄升序
            }
        });
        //2.添加学生
        while (true){
            System.out.println("请输入学生id：");
            String id = sc.next();
            if (id.equals("exit")){
                break;
            }
            System.out.println("请输入学生姓名：");
            String name = sc.next();
            if (name.equals("exit")){
                break;
            }
            System.out.println("请输入学生年龄：");
            int age = sc.nextInt();
            ts.add(new Student(id,name,age));
        }

        //3.遍历集合
        for (Student student : ts) {
            System.out.println(student);
        }
        //4.写入文件,使用PrintWriter
        try (PrintWriter pw = new PrintWriter("day12-code/src/exam/A.txt")) {
            for (Student t : ts) {
                pw.println(t);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
class Student implements Serializable {
    @Serial
    private static final long serialVersionUID = -2943985611226332967L;
    private String id;
    private String name;
    private Integer age;

    public Student() {}

    public Student(String id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id) && Objects.equals(name, student.name) && Objects.equals(age, student.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age);
    }

    @Override
    public String toString() {
        return "学号：" + id + "，姓名：" + name + "，年龄：" + age;
    }
}
